﻿@model IList<ShoppingCartModel.CheckoutAttributeModel>
@using Grand.Core.Domain.Catalog;
@using Grand.Core.Domain.Media
@using System.Text;
@inject Grand.Services.Media.IDownloadService downloadService
@if (Model.Any())
{
    var attributeChangeScriptsBuilder = new StringBuilder();
    <div class="checkout-attributes p-0">
        @foreach (var attribute in Model)
        {
            string controlId = string.Format("checkout_attribute_{0}", attribute.Id);
            string textPrompt = !string.IsNullOrEmpty(attribute.TextPrompt) ? attribute.TextPrompt : attribute.Name;
            <div id="@string.Format("checkout_attribute_label_{0}", attribute.Id)" class="col-12 px-0">
                <span class="col-form-label text-prompt">
                    @textPrompt
                </span>
                @if (attribute.IsRequired)
                {
                    <span class="required">*</span>
                }
                @switch (attribute.AttributeControlType)
                {
                    case AttributeControlType.TextBox:
                        {
                            <label for="@(controlId)" class="sr-only">"@(controlId)</label>
                            <input name="@(controlId)" type="text" class="form-control textbox" id="@(controlId)" value="@(attribute.DefaultValue)" onchange="checkoutAttributeChange()" />
                        }
                        break;
                    case AttributeControlType.DropdownList:
                        {
                            <label for="@(controlId)" class="sr-only">"@(controlId)</label>
                            <select id="@(controlId)" class="form-control custom-select" name="@(controlId)">
                                @if (!attribute.IsRequired)
                                {
                                    <option value="0">---</option>
                                }
                                @foreach (var attributeValue in attribute.Values)
                                {
                                    var attributeName = String.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                        attributeValue.Name :
                                        T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                    <option selected="@attributeValue.IsPreSelected" value="@attributeValue.Id">@attributeName</option>
                                }
                            </select>
                            attributeChangeScriptsBuilder.AppendFormat("$('#{0}').change(function(){{checkoutAttributeChange();}});\n", controlId);
                        }
                        break;
                    case AttributeControlType.RadioList:
                        {
                            <ul class="option-list pl-0">
                                @foreach (var attributeValue in attribute.Values)
                                {
                                    var attributeName = String.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                        attributeValue.Name :
                                        T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                    <li>
                                        <fieldset>
                                            <legend class="sr-only">
                                                @(controlId)
                                            </legend>
                                            <label class="custom-control custom-radio">
                                                <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                                <span class="custom-control-label"></span>
                                                <span class="custom-control-description" for="@(controlId)_@(attributeValue.Id)">@attributeName</span>
                                            </label>

                                        </fieldset>
                                    </li>
                                    attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').click(function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                }
                            </ul>
                        }
                        break;
                    case AttributeControlType.Checkboxes:
                    case AttributeControlType.ReadonlyCheckboxes:
                        {
                            <fieldset>
                                <legend></legend>
                                <ul class="option-list pl-0">
                                    @foreach (var attributeValue in attribute.Values)
                                    {
                                        var attributeName = String.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                            attributeValue.Name :
                                            T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                        <li>
                                            <label class="custom-control custom-checkbox">
                                                <input class="custom-control-input" id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null) />
                                                <span class="custom-control-label"></span>
                                                <span class="custom-control-description" for="@(controlId)_@(attributeValue.Id)">@attributeName</span>
                                            </label>
                                        </li>
                                        attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').click(function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                    }
                                </ul>
                            </fieldset>
                        }
                        break;

                    case AttributeControlType.MultilineTextbox:
                        {
                            <textarea id="@(controlId)" name="@(controlId)" onchange="checkoutAttributeChange()">@(attribute.DefaultValue)</textarea>
                        }
                        break;
                    case AttributeControlType.Datepicker:
                        {
                            <date-picker-dropdown control-day="@(controlId + "_day")"
                                                  control-month="@(controlId + "_month")"
                                                  control-year="@(controlId + "_year")"
                                                  begin-year="@(DateTime.Now.Year)"
                                                  end-year="@(DateTime.Now.Year+1)"
                                                  selected-day="(attribute.SelectedDay.HasValue ? attribute.SelectedDay.Value : 0)"
                                                  selected-month="(attribute.SelectedMonth.HasValue ? attribute.SelectedMonth.Value : 0)"
                                                  selected-year="(attribute.SelectedYear.HasValue ? attribute.SelectedYear.Value : 0)"
                                                  class="input-group" />

                        }
                        break;
                    case AttributeControlType.FileUpload:
                        {
                            Download download = null;
                            if (!String.IsNullOrEmpty(attribute.DefaultValue))
                            {
                                download = await downloadService.GetDownloadByGuid(new Guid(attribute.DefaultValue));
                            }

                            //register CSS and JS
                            Html.AddCssFileParts("~/scripts/fineuploader/fineuploader-4.2.2.min.css");
                            Html.AddScriptParts(ResourceLocation.Footer, "~/scripts/fineuploader/jquery.fineuploader-4.2.2.min.js");

                            //ex. ['jpg', 'jpeg', 'png', 'gif'] or []
                            var allowedFileExtensions = string.Join(", ", attribute.AllowedFileExtensions.Select(x => "'" + x.Trim() + "'").ToList());

                            if (download != null)
                            {
                                <input id="@(controlId)" name="@(controlId)" type="hidden" value="@download.DownloadGuid" />
                            }
                            else
                            {
                                <input id="@(controlId)" name="@(controlId)" type="hidden" />
                            }

                            @*fine uploader container*@
                            <div id="@(controlId)uploader"></div>
                            @*fine uploader template (keep it synchronized to \Content\fineuploader\templates\default.html)*@
                            <script type="text/template" id="@(controlId)-qq-template">
                                <div class="qq-uploader-selector qq-uploader">
                                    <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                                        <span>@T("Common.FileUploader.DropFiles")</span>
                                    </div>
                                    <div class="qq-upload-button-selector qq-upload-button">
                                        <div>@T("Common.FileUploader.Upload")</div>
                                    </div>
                                    <span class="qq-drop-processing-selector qq-drop-processing">
                                        <span>@T("Common.FileUploader.Processing")</span>
                                        <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
                                    </span>
                                    <ul class="qq-upload-list-selector qq-upload-list">
                                        <li>
                                            <div class="qq-progress-bar-container-selector">
                                                <div class="qq-progress-bar-selector qq-progress-bar"></div>
                                            </div>
                                            <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                                            <span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
                                            <span class="qq-upload-file-selector qq-upload-file"></span>
                                            <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                                            <span class="qq-upload-size-selector qq-upload-size"></span>
                                            <a class="qq-upload-cancel-selector qq-upload-cancel" href="#">@T("Common.FileUploader.Cancel")</a>
                                            <a class="qq-upload-retry-selector qq-upload-retry" href="#">@T("Common.FileUploader.Retry")</a>
                                            <a class="qq-upload-delete-selector qq-upload-delete" href="#">@T("Common.FileUploader.Delete")</a>
                                            <span class="qq-upload-status-text-selector qq-upload-status-text"></span>
                                        </li>
                                    </ul>
                                </div>
                            </script>
                            <script asp-location="Footer">
                                    $(document).ready(function() {
                                        $("#@(controlId)uploader").fineUploader({
                                            request: {
                                                endpoint: '@(Url.RouteUrl("UploadFileCheckoutAttribute", new {attributeId = attribute.Id}))'
                                            },
                                            template: "@(controlId)-qq-template",
                                            multiple: false,
                                            validation: {
                                                allowedExtensions: [@Html.Raw(allowedFileExtensions)]
                                            }
                                        }).on("complete", function(event, id, name, responseJSON, xhr) {
                                            $("#@(controlId)").val(responseJSON.downloadGuid);
                                            if (responseJSON.success) {
                                                $("#@(controlId + "downloadurl")").html("<a href='" + responseJSON.downloadUrl + "'>@T("Common.FileUploader.DownloadUploadedFile")</a>");
                                                $("#@(controlId + "remove")").show();
                                                checkoutAttributeChange();
                                            }
                                            if (responseJSON.message) {
                                                alert(responseJSON.message);
                                            }
                                        });

                                        $("#@(controlId + "remove")").click(function(e) {
                                            $("#@(controlId + "downloadurl")").html("");
                                            $("#@(controlId)").val('');
                                            $(this).hide();
                                            checkoutAttributeChange();
                                        });
                                    });
                            </script>
                            <div id="@(controlId + "downloadurl")">
                                @if (download != null)
                                {
                                    <a href="@(Url.Action("GetFileUpload", "Download", new { downloadId = download.DownloadGuid }))" class="download-uploaded-file">@T("Common.FileUploader.DownloadUploadedFile")</a>
                                }
                            </div>
                            <div>
                                @if (download != null)
                                {
                                    <a id="@(controlId + "remove")" class="remove-download-button">@T("Common.FileUploader.RemoveDownload")</a>
                                }
                                else
                                {
                                    <a id="@(controlId + "remove")" class="remove-download-buttonn" style="display:none;">@T("Common.FileUploader.RemoveDownload")</a>
                                }
                            </div>
                        }
                        break;
                    case AttributeControlType.ColorSquares:
                        {
                            <ul class="option-list color-squares pl-0" id="color-squares-@(attribute.Id)">
                                @foreach (var attributeValue in attribute.Values)
                                {
                                    var attributeName = String.IsNullOrEmpty(attributeValue.PriceAdjustment) ?
                                        attributeValue.Name :
                                        T("ShoppingCart.CheckoutAttributes.PriceAdjustment", attributeValue.Name, attributeValue.PriceAdjustment).Text;
                                    <li class="mr-1 p-0" @(attributeValue.IsPreSelected ? @Html.Raw(" class=\"selected-value border border-primary\"") : null)>
                                        <label for="@(controlId)_@(attributeValue.Id)" class="mb-0">
                                            <span class="color-container" title="@attributeName">
                                                <span class="color" style="background-color:@(attributeValue.ColorSquaresRgb);">&nbsp;</span>
                                            </span>
                                            <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected" />
                                            @*uncomment below to display attribute value name*@
                                            @*<span class="name">@attributeName</span>*@
                                        </label>
                                    </li>
                                    attributeChangeScriptsBuilder.AppendFormat("$('#{0}_{1}').click(function(){{checkoutAttributeChange();}});\n", controlId, attributeValue.Id);
                                }
                            </ul>
                            <script asp-location="Footer">
                                    $(document).ready(function() {
                                        $('.checkout-attributes #color-squares-@(attribute.Id)').delegate('input', 'click', function (event) {
                                            $('.checkout-attributes #color-squares-@(attribute.Id)').find('li').removeClass('selected-value border border-primary');
                                            $(this).closest('li').addClass('selected-value border border-primary');
                                        });
                                   });
                            </script>
                        }
                        break;
                    case AttributeControlType.ImageSquares:
                        {
                            //not support attribute type
                        }
                        break;
                }
            </div>
        }
    </div>

    <script asp-location="Footer">
        $(document).ready(function() {
            checkoutAttributeChange();
            @Html.Raw(attributeChangeScriptsBuilder.ToString())
        });

        function checkoutAttributeChange() {
            $.ajax({
                cache: false,
                url: '@Html.Raw(Url.Action("checkoutattributechange", "shoppingcart"))',
                data: $('#shopping-cart-form').serialize(),
                type: 'post',
                success: function(data) {
                    if (data.enabledattributeids) {
                        for (var i = 0; i < data.enabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.enabledattributeids[i]).show();
                            $('#checkout_attribute_input_' + data.enabledattributeids[i]).show();
                        }
                    }
                    if (data.disabledattributeids) {
                        for (var i = 0; i < data.disabledattributeids.length; i++) {
                            $('#checkout_attribute_label_' + data.disabledattributeids[i]).hide();
                            $('#checkout_attribute_input_' + data.disabledattributeids[i]).hide();
                        }
                    }
                    if (data.htmlordertotal) {
                        $('.total-info').replaceWith(data.htmlordertotal);
                    }
                    if (data.checkoutattributeinfo) {
                        $('.selected-checkout-attributes').html(data.checkoutattributeinfo);
                    }
                }
            });
        }
    </script>
}